#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include"CartridgeBoard.h"

bool LoadRom(CARTRIDGEBOARD*cart,PCTSTR szFilePath);

void CartridgeBoardInit(CARTRIDGEBOARD* cart)
{
	memset(&cart->Header, 0, sizeof(&cart->Header));
	cart->Trainer = cart->ChrRom = cart->PrgRom = NULL;

	cart->LoadRom = LoadRom;
}
void CartridgeBoardFree(CARTRIDGEBOARD* cart)
{
	if (cart->Trainer)
		free(cart->Trainer);
	if (cart->ChrRom)
		free(cart->ChrRom);
	if (cart->PrgRom)
		free(cart->PrgRom);
}
bool LoadRom(CARTRIDGEBOARD *cart,PCTSTR szFilePath)
{
	FILE* fp;

#ifdef UNICODE
	fp = _wfopen(szFilePath, TEXT("rb"));
#else
	fp = fopen(szFilePath, "rb");
#endif

	if (fp == NULL)
		return false;

	fread(&cart->Header, sizeof(cart->Header), 1, fp);
	cart->PrgRom = (uint8_t*)malloc(cart->Header.PrgSize * 0x4000);
	cart->ChrRom = (uint8_t*)malloc(cart->Header.ChrSize * 0x2000);

	if (cart->Header.Flag6 & TRAINER)
	{
		cart->Trainer = (uint8_t*)malloc(512);
		fread(cart->Trainer, 512, 1, fp);
	}
	fread(cart->PrgRom, cart->Header.PrgSize * 0x4000, 1, fp);
	fread(cart->ChrRom, cart->Header.ChrSize * 0x2000, 1, fp);

	fclose(fp);
	return true;
}